package com.tjzx.common;

/**
 * 
 */

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @category 字符编码过滤
 * 
 * @author Beyond
 */
public class EncodingFilter implements Filter {
	
	private FilterConfig filterConfig = null;

	private String encoding = null; // 系统默认的字符编码集
	
	private boolean isIgnore = true; // 是否忽略服务器字符编码

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy(){
		this.filterConfig = null;
		this.encoding = null;
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 * 
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.encoding = this.filterConfig.getInitParameter("encoding");
		String igonreValue = this.filterConfig.getInitParameter("ignore");
		
		if (igonreValue == null) {
			this.isIgnore = true;
		} else {
			if (igonreValue.equalsIgnoreCase("true")) {
				this.isIgnore = true;
			} else { 
				if (igonreValue.equalsIgnoreCase("yes")) {
					this.isIgnore = true;
				} else {
					this.isIgnore = false;
				}
			}
		}
	}

	/**
	 * set character encoding <br>
	 * 
	 * @throws ServletException
	 */
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain){
		if (isIgnore || (request.getCharacterEncoding() == null)){
			if (this.encoding != null) {
				try {
					request.setCharacterEncoding( this.encoding );
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		
		try {
			filterChain.doFilter(request, response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
